package com.inspectortime.mail.service;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * Represents an e-mail message that is based on a Freemarker template file
 * 
 * @author mkvalsvik
 * 
 */
public class StaticMailMessage extends AbstractMailMessage {

	private String bodyTemplateFileName;

	public StaticMailMessage(String bodyTemplateFileName, Map<String, Object> data, String to, String subject) {
		this.bodyTemplateFileName = bodyTemplateFileName;
		this.setData(data);
		this.setTo(to);
		this.setSubject(subject);
	}

	public String getBodyTemplateFileName() {
		return bodyTemplateFileName;
	}
	
	/**
	 * Perform no conversion, assumes that static templates have properly formatted HTML in them already
	 */
	public String getBodyHtml() {
		return this.getBody();
	}

	public void setBodyTemplateFileName(String bodyTemplateFileName) {
		this.bodyTemplateFileName = bodyTemplateFileName;
	}

	public void processTemplates(Configuration freemarkerConfiguration)
			throws EmailDeliveryException {
		StringWriter writer = null;
		Template template;
		try {
			template = freemarkerConfiguration.getTemplate(bodyTemplateFileName);
		writer = new StringWriter();
		template.process(getData(), writer);
		this.setBody(writer.toString());
		} catch (IOException e) {
			throw new EmailDeliveryException("IO error related to template file " + bodyTemplateFileName, e);
		} catch (TemplateException e) {
			throw new EmailDeliveryException("Improperly formatted template file " + bodyTemplateFileName, e);
		}
	}

}
